<template>
  <div style="display: flex; flex-direction: column; height: calc(100vh - 102px)">
    <div>
      <div class="headButton">
        <div>
          <span class="title">{{'项目任务-'}}<a @click.prevent="goBack" class="back-class" href="#">计划详情</a></span>
        </div>
        <div>
          <el-button @click="yjOpenClose">一键展开/收起</el-button>
<!--          <span><el-button @click="gotoBack">{{ isQieHuan ? '资源管理' : '返回' }}</el-button></span>-->
          <button-popver btnLabel="新建" trigger="hover" ref="newPopver">
            <div style="display: flex; flex-direction: column;justify-content: start">
              <el-button @click="add()" icon="el-icon-plus" size="medium" style="margin-left: 0" type="text">新建分组</el-button>
              <el-divider class="divider"/>
              <el-button @click="addMilestone" icon="el-icon-s-flag" size="medium" type="text">添加里程碑</el-button>
            </div>
          </button-popver>
          <el-divider direction="vertical"/>
          <el-button icon="el-icon-full-screen" type="text" size="medium" style="margin-left: 10px" @click="fullscreen"></el-button>
          <span style="margin-left: 10px">计划：{{this.time(planData.Started)}}-{{this.time(planData.Ended)}}</span>
        </div>
      </div>
<!--      <search-component v-if="isQieHuan" :colum="colum" :formValue="formValue" class="search"-->
<!--                              @search="searchData" @reset="reset" ref="search">-->
<!--      </search-component>-->

    </div>
    <div style="position: relative;">
      <div style="display: flex; justify-content: space-between; align-items: center">
        <div>总任务数: {{totalTaskCount.taskCount}}, 总分组数: {{ totalTaskCount.gounp }}, 里程碑：{{totalTaskCount.Classify3}}</div>
        <div class="vxe-icon--funnel" @click.prevent="showSearch = !showSearch"></div>
      </div>
      <gtt-component ref="gtt" @milestoneVisible="milestoneVisibleF" :planData.sync="planData"
                     @modifyTask="add" v-show="isQieHuan" @xiugaiTime="xiugaiTime"
                     @addDdlVisible="showTaskAdd" @switchTask="switchTask"
                     @addVisible="add"></gtt-component>
      <scheduler-table :planData="planData" v-show="!isQieHuan" ref="schedulerTable"></scheduler-table>
      <el-card v-show="showSearch" style="overflow: auto; position: absolute; width: 300px; height: calc(100% - 54px); top: 24px; right: 0; z-index: 100">
        <el-form>
          <el-form-item v-for="item in colum" :key="item.prop">
            <component :is="item.componentName" v-bind="item" v-model="formValue[item.prop]"
                       @input="componentNameSu(item.prop).componentNameInput" style="width: 100%"
                       @selectChanged="componentNameSu(item.prop).componentNameSelectChanged"></component>
          </el-form-item>
          <el-form-item style="display: flex; justify-content: center">
            <vxe-button class="search-class" status="primary" size="small" v-throttle="[searchData, `click`, 300]">查询</vxe-button>
            <vxe-button size="small" @click="reset">重置</vxe-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div v-if="showSearch" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: 99" @click="showSearch = false"></div>
    <TaskAssigned :visible.sync="modalVisible" title="任务指派" :formData="formData" @search="searchData"></TaskAssigned>
    <taskAddDialog :visible.sync="addVisible" :Title="taskAddDialogTitle" :formData="addData" @close="searchData"></taskAddDialog>
    <TaskAdd :visible.sync="addtaskVisible" :Title="'新增任务'" :formData="addData" @close="searchData"></TaskAdd>
    <milestone-dialog :title="'新增里程碑'" :preFormData="milestoneFormData" :visible.sync="milestoneVisible" @close="searchData"></milestone-dialog>
    <dialog-task :visible.sync="switchTaskGroup" :Title="'切换任务分组'" :formData="switchTaskGroupData" :queryValue="queryValue" @switchParenttas="switchParenttas"></dialog-task>
    <working-hours-add :modelType="modelType" :visible.sync="workingHoursAddVisible" :formData="workingHoursItem" @close="searchData"></working-hours-add>
    <zhipai-dialog :visible.sync="zhipaiVisible" :formData="workingHoursItem" @close="searchData"></zhipai-dialog>
    <dialog-view :modelType="modelType" :visible.sync="dialogView" :formData="workingHoursItem" @close="searchData"></dialog-view>
  </div>
</template>

<script>
import searchComponent from "@/components/element/layoutComponents/searchFrom/searchComponent.vue";
import DictionarySelect from "@/components/element/DictionarySelect";
import SelectProjectModule from "@/components/element/select/SelectProjectModule";
import SelectProjectTeam from "@/components/element/select/SelectProjectTeam";
import projectTaskApi from "@/api/projectTaskApi";
import TaskAssigned from "./TaskAssigned";
import TaskEdit from "./TaskEdit";
import taskAddDialog from "@/page/ProjectManage/modules/task/taskAddDialog";
import TaskAdd from "./TaskAdd.vue";
import MilestoneDialog from "./MilestoneDialog";
import * as format from '@/filters/index'
import bus from '@/components/common/bus';
import GttComponent from "@/page/ProjectManage/modules/taskModule/gttcom/gttComponent";
import projectPlanApi from "@/api/projectPlanApi";
import buttonPopver from "@/components/element/selectClickPopover/buttonPopver";
import schedulerTable from "@/page/ProjectManage/modules/taskModule/gttcom/schedulerTable";
import dialogTask from "@/page/ProjectManage/modules/taskModule/dialogTask";
import workingHoursAdd from "./workingHoursAdd";
import zhipaiDialog from "@/page/ProjectManage/modules/taskModule/zhipaiDialog";
import dialogView from "@/page/ProjectManage/modules/taskModule/dialogView";
import store from '@/store';

export default {
  name: 'projectTask',
  components: {
    dialogView,
    zhipaiDialog,
    dialogTask,
    workingHoursAdd,
    GttComponent,
    searchComponent,
    TaskAssigned,
    TaskEdit,
    taskAddDialog,
    SelectProjectTeam,
    MilestoneDialog,
    TaskAdd,
    buttonPopver,
    schedulerTable
  },
  mounted() {
    this.searchData()
    let that = this
    bus.$on('showTaskByIdClose', (a) => {
      that.isSearch = true
    })
  },
  activated() {
    if (this.isSearch) {
      this.isSearch = false
      this.searchData()
    }
  },
  computed: {
    linkName () {
      return (row) => {
        let hp = window.location.protocol
        let host = window.location.host
        return `${hp}//${host}/view/task/show/${row.Id}`
      }
    },
    formatDatetime() {
      return (val) => {
        let a = format.formatDatetime(val)
        if (a.indexOf('1970') >= 0) {
          return ''
        } else {
          return a
        }
      }
    }
  },
  data() {
    return {
      dialogView: false,
      modelType: 0,
      zhipaiVisible: false,
      workingHoursItem: {},
      workingHoursAddVisible: false,
      showSearch: false,
      totalTaskCount: {},
      switchTaskGroup: false,
      switchTaskGroupData: {},
      queryValue: {},
      isQieHuan: true,

      taskAddDialogTitle: '添加分组',
      addtaskVisible: false,
      tableModel: ['年', '月'],
      preTableModelStr: ['年'],
      tableModelStr: ['年'],
      milestoneFormData: {},
      milestoneVisible: false,
      planData: {},
      noShowGtt: false,
      isSearch: false,
      loading: false,
      formData: {},
      modalVisible: false,
      addData: {},
      addVisible: false,
      formValue: {},
      colum: [
        {
          placeholder: '请选择模块',
          prop: 'moduleid',
          size: 'small',
          componentName: SelectProjectModule,
          data: 'URL',
          value: 'moduleid',
          clearable: true,
          ref: 'moduleid',
          show: true,
          multiple: true,
          attrs: {
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择负责人',
          selectTitle: '负责人',
          prop: 'acceptid',
          size: 'small',
          componentName: SelectProjectTeam,
          value: 'acceptid',
          ref: 'acceptid',
          clearable: true,
          show: true,
          multiple: true,
          attrs: {
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择对应人',
          selectTitle: '对应人',
          prop: 'qzAcceptid',
          size: 'small',
          componentName: SelectProjectTeam,
          value: 'qzAcceptid',
          ref: 'qzAcceptid',
          clearable: true,
          show: true,
          multiple: true,
          attrs: {
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请输入任务编号',
          prop: 'tasktno',
          size: 'small',
          componentName: 'vxe-input',
          value: 'tasktno',
          clearable: true,
          show: true,
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请输入任务名称',
          prop: 'name',
          size: 'small',
          componentName: 'vxe-input',
          min: 0,
          value: 'name',
          clearable: true,
          show: true,
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请输入反馈编号',
          prop: 'Testid',
          size: 'small',
          componentName: 'vxe-input',
          min: 0,
          value: 'Testid',
          clearable: true,
          show: true,
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择任务状态',
          prop: 'status',
          size: 'small',
          dictTypeCode: 'TASK_STATUS',
          componentName: DictionarySelect,
          value: 'status',
          clearable: true,
          show: true,
          multiple: true,
          elcolStyle: {
            'width': '200px'
          }
        }
      ],
      tableData: []
    }
  },
  methods: {
    // 修改工时
    xiugaiTime (taskid, type) {
      this.modelType = type
      this.workingHoursItem = this.tableData.find(it => it.Id === taskid) || {}
      if (type === 2) {
        // 预计工时
        this.workingHoursAddVisible = true
      } else if (type === 1) {
        // 指派
        this.zhipaiVisible = true
      } else if (type === 3) {
        // 实际工时
        this.dialogView = true
      } else if (type === 4) {
        // 认定工时
        // this.workingHoursAddVisible = true
        this.warning('功能开发中')
      }
    },
    // yjOpenClose
    yjOpenClose () {
      this.$refs.gtt.yjOpenClose()
    },
    trimValue (val) {
      if (!Array.isArray(val)) {
        if (typeof val === 'string') {
          return (val || '').trim()
        }
      }
      return val
    },
    componentNameSu (prop) {
      let componentNameInput = (object) => {
        if (!object || object.length === 0) {
          this.$set(this.formValue, prop, undefined)
        } else {
          this.$set(this.formValue, prop, this.trimValue(object))
        }
      }
      let componentNameSelectChanged = (object) => {
        this.$set(this.formValue, prop, object)
      }
      return {
        componentNameInput, componentNameSelectChanged
      }
    },
    switchParenttas () {
      this.searchData()
    },
    // 切换任务
    switchTask (task) {
      this.switchTaskGroupData = task
      this.switchTaskGroup = true
    },
    // 切换
    gotoBack () {
      this.isQieHuan = !this.isQieHuan
      if (!this.isQieHuan) {
        this.$refs.schedulerTable.getDataByAll()
      }
    },
    // 全屏显示
    fullscreen () {
      this.$refs.gtt.fullscreen()
    },
    groupChange (a) {
      if (JSON.stringify(a) !== JSON.stringify(this.preTableModelStr)) {
        a.splice(a.indexOf(this.preTableModelStr), 1)
        this.tableModelStr = a
        this.preTableModelStr = this.tableModelStr
      }
    },
    // init初始化
    initProject () {
      let that = this
      setTimeout(function () {
        that.colum.forEach(it => {
          if (it.prop === 'acceptid'|| it.prop === 'moduleid' || it.prop === 'qzAcceptid') {
            // this.$set(it, 'attrs', it.attrs || {})
            that.$set(it, 'queryValue', {
              id: that.planData.Projectid
            })
          }
        })
      }, 1000)
    },
    // 时间
    time (time) {
      if (!time) return ''
      return format.formatDatetime(time, 'yyyy:MM:dd')
    },
    // 里程碑编辑
    milestoneVisibleF (data) {
      this.milestoneFormData = Object.assign(data, {
        Projectid: this.planData.Projectid,
        Planid: this.planData.Id
      })
      this.milestoneVisible = true
    },
    // 添加里程碑
    addMilestone () {
      this.$refs.newPopver.btnTrigger()
      this.milestoneFormData = {
        Projectid: this.planData.Projectid,
        Planid: this.planData.Id
      }
      this.milestoneVisible = true
    },
    // showTaskAdd
    showTaskAdd (data, type) {
      let wData = JSON.parse(JSON.stringify(data))
      if (type === 'add' || type === 'addChild') {
        if (wData.Stage !== 8 && wData.Stage !== 9 && wData.Stage !== 10) {
          if (wData.Acceptid !== store.getters.userId) {
            return this.$message.error('请联系此分组负责人创建');
          }
        }
        data = {}
        if (!data.hasOwnProperty('Projectid')) {
          this.$set(data, 'Projectid', this.planData.Projectid)
        }
        if (!data.hasOwnProperty('Planid')) {
          this.$set(data, 'Planid', this.planData.Id)
        }
        if (!data.hasOwnProperty('PlanStarted')) {
          this.$set(data, 'PlanStarted', this.planData.Started)
        }
        if (!data.hasOwnProperty('Testid') && wData) {
          this.$set(data, 'Testid', wData.Testid)
        }
        if (!data.hasOwnProperty('TestName') && wData) {
          this.$set(data, 'TestName', wData.Testname)
        }
        if (wData.Id && wData.Id !== '0') {
          this.$set(data, 'Parenttaskid', wData.Id)
        }
      }
      if (data.Id) {
        this.$router.push(`/view/taskEdit/${data.Id}`)
      } else {
        this.addData = data
        this.addtaskVisible = true
      }
    },
    // 查询
    searchData () {
      this.showSearch = false
      if (Object.keys(this.planData).length === 0) {
        this.initSearchP().then(res => {
          this.planData = res
          this.initProject()
          this.search()
        })
      } else {
        this.initProject()
        this.search()
      }
      let query=this.formValue
      gantt.attachEvent("onBeforeTaskDisplay", function(id, task){
        if (query.moduleid === undefined){
          return true;
        }else {
          return true;
        }
      });
    },
    // 去甘特图
    goGantt () {
      let that = this
      that.noShowGtt = !that.noShowGtt
      if (!that.noShowGtt) {
        that.$nextTick(_ => {
          that.$refs.gtt.showTaskLists(that.tableData)
        })
      }
    },
    checkComper (row) {
      let rEnded = row.Ended
      if (rEnded === 0) return ''
      if ((rEnded * 1000) < Date.now() && row.Status < 3) {
        return '延期'
      }
    },
    rowClassName ({ row, rowIndex }) {
      if (row.Status === 3) return 'ok-col-red'
      let rEnded = row.Ended
      if (rEnded === 0) return ''
      if ((rEnded * 1000) < Date.now() && row.Status < 3) {
        return 'col-red'
      }
      return 'col-defa'
    },
    // 添加任务
    addChildTask (row) {
      this.addData = {
        Parenttaskid: row.Id,
        PlanStarted: this.formData.Started
      }
      this.addVisible = true
    },
    // 返回项目详情
    goBack () {
      this.$router.push(`/view/project/plan/${this.planData.Projectid}`)
    },
    changeStatus(row, val) {
      let obj = {
        id: row.Id,
        status: val
      }
      projectTaskApi.status(obj).then(res => {
        this.$XModal.message({message: res.message, status: res.code === 1 ? 'success' : 'error'})
        this.$emit('search')
        if (res.code === 1) this.modalVisible = false
      })
    },
    edit(row) {
      this.$router.push(`/view/task/show/${row.Id}`)
    },
    add(data) {
      this.addData = {
        Projectid: this.planData.Projectid,
        Planid: this.planData.Id,
        PlanStarted: this.planData.Started
      }
      // if (this.planData.Createid !== store.getters.userId) {
      //   return this.$message.error('请联系计划管理者创建、修改');
      // }
      if (data) {
        this.addData = Object.assign(this.addData, {
          id: data.Id
        })
        this.taskAddDialogTitle = '修改分组'
      } else {
        this.$refs.newPopver.btnTrigger()
        this.taskAddDialogTitle = '新增分组'
      }
      this.addVisible = true
    },
    assigned(row) {
      this.formData = {
        Completeid: '',
        acceptid: '',
        Id: row.Id,
        qzAcceptid: '',
        note: ''
      }
      this.modalVisible = true
    },
    queryChange(val) {
      //
      this.formValue = {}
      if (val === 'userid') {
        this.$set(this.formValue, 'userid', [ this.$store.getters.userId ])
      }
      this.searchData()
    },
    search() {
      this.tableData = []
      let query1 = Object.assign({
        id: this.planData.Projectid,
        planid: this.planData.Id,
      }, this.formValue)
      let query = JSON.parse(JSON.stringify(query1))
      this.queryValue = query
      this.loading = true
      projectTaskApi.getPage(query).then(res => {
        let b = []
        if (res) {
          // this.tableData = this.localSearch(res, query)
          // this.tableData =res
          b = res;
        }
        this.totalTaskCount = this.getTotalTaskCount(b)
        // console.log(this.totalTaskCount)
        this.tableData = this.localSearch(b, query)
        // console.log(b);
        this.$nextTick(() => {
          if (!this.noShowGtt && this.$refs.gtt) {
            this.$refs.gtt.showTaskLists(this.tableData)
          }
        })
      }).catch((e) => {
        this.$message.error('获取任务信息失败')
      }).finally(() => this.loading = false);
    },
    // ；localSearch
    localSearch (data, formData) {
      // console.log(data, formData)
      let a = data.filter(it => {
        let qzacceptid = true, acceptid = true, moduleid = true, name = true, Testid = true, tasktno = true, status = true
        if ((formData.acceptid && formData.acceptid.length > 0) && (formData.qzAcceptid && formData.qzAcceptid.length > 0)) {
          acceptid = formData.acceptid.some(it1 => it1 === it.Acceptid.toString()) || formData.qzAcceptid.some(it1 => it1 === it.Acceptid.toString())
        } else if (formData.acceptid && formData.acceptid.length > 0) {
          acceptid = formData.acceptid.some(it1 => it1 === it.Acceptid.toString())
        } else if (formData.qzAcceptid && formData.qzAcceptid.length > 0) {
          qzacceptid = formData.qzAcceptid.some(it1 => it1 === it.Acceptid.toString())
        }
        if (formData.moduleid && formData.moduleid.length > 0) {
          moduleid = formData.moduleid.some(it1 => it1 === it.Moduleid.toString())
        }
        if (formData.tasktno && formData.tasktno.length > 0) {
          tasktno = it.Id.toString() === formData.tasktno
        }
        if (formData.name && formData.name.length > 0) {
          name = it.Name.toString().indexOf(formData.name) >= 0
        }
        if (formData.Testid && formData.Testid.length > 0) {
          Testid = it.Testid.toString().indexOf(formData.Testid) >= 0
        }
        if (formData.status && formData.status.length > 0) {
          status = formData.status.some(it1 => it1.toString() === it.Status.toString())
        }
        // console.log(acceptid, moduleid, tasktno, status)
        return qzacceptid && acceptid && moduleid && tasktno && status && name && Testid
      })
      if ((formData.qzAcceptid && formData.qzAcceptid.length > 0) && (formData.acceptid && formData.acceptid.length > 0)) {
        let w = []
        a.forEach(it => {
          w.push(it)
          this.a_bAdd(a, it, data, w)
        })
        w = this.requerC(w)
        return w
      }
      // 对应人---只往上找
      else if (formData.qzAcceptid && formData.qzAcceptid.length > 0) {
        let w = []
        a.forEach(it => {
          w.push(it)
          if (it.Parenttaskid) this.showParent(it.Parenttaskid, w, data)
        })
        w = this.requerC(w)
        return w
      }
      // 负责人---只往下找
      else if (formData.acceptid && formData.acceptid.length > 0) {
        let wc = []
        a.forEach(it => {
          wc.push(it)
          this.showChild(it.Id, wc, data)
        })
        let w = JSON.parse(JSON.stringify(wc))
        w.forEach(it => {
          this.a_bAdd(w, it, data, wc)
        })
        wc = this.requerC(wc)
        return wc
      } else {
        let wc = []
        let w = JSON.parse(JSON.stringify(a))
        a.forEach(it => {
          wc.push(it)
          this.a_bAdd(w, it, data, wc)
        })
        wc = this.requerC(wc)
        return wc
      }
    },
    // 一层层的往上找
    a_bAdd (a, it, data, w) {
      if (!a.some(it1 => it1.Id === it.Parenttaskid)) {
        let x = data.find(it1 => it1.Id === it.Parenttaskid)
        if (x) {
          w.push(x)
          return this.a_bAdd(a, x, data, w)
        }
      }
    },
    // 去重
    requerC (wc) {
      let a = {}
      wc.forEach(it => {
        a[it.Id] = it
      })
      return Object.values(a)
    },
    // 获取总任务数
    getTotalTaskCount (res) {
      let ww = res.filter(it => {
        return it.Classify !== '3'
      })
      let w = []
      let Parenttaskids = (ww||[]).filter(it => it.Parenttaskid === '0')
      if (Parenttaskids.length > 0) {
        this.hanldChild((ww||[]), Parenttaskids, w)
      }
      let acount = {
        acount: {}
      }
      this.getAcount(w, acount)
      return {
        gounp: Parenttaskids.length,
        taskCount: Object.keys(acount.acount).length,
        Classify3: res.filter(it => {
          return it.Classify === '3'
        }).length
      }
    },
    getAcount (ww, tj) {
      ww.forEach(it => {
        if (it.Parenttaskid) {
          if (!it.children && it.Parenttaskid !== '0') {
            this.$set(tj.acount, `${it.Id}`, 1)
          }
          else this.getAcount(it.children || [], tj)
        }
      })
    },
    hanldChild (data, Parenttaskids, w) {
      Parenttaskids.forEach(it => {
        let t = data.filter(it1 => it1.Parenttaskid === it.Id)
        if (t.length > 0) {
          if (!it.hasOwnProperty('children')) {
            this.$set(it, 'children', [])
          }
          it.children.push(...t)
          this.hanldChild(data, it.children || [], w)
          w.push(it)
        }
      })
    },
    // 查询所有父类
    showParent (Parenttaskid, w, data) {
      let a = data.findIndex(it => it.Id === Parenttaskid)
      if (a >= 0) {
        w.push(data[a])
        if (data[a].Parenttaskid) this.showParent(data[a].Parenttaskid, w, data)
      }
    },
    // 查询所有子类
    showChild (id, w, data) {
      let a = data.filter(it => {
        return it.Parenttaskid && it.Parenttaskid.toString().length > 5 && it.Parenttaskid === id
      })
      if (a.length > 0) {
        w.push(...a)
        a.forEach(it => {
          this.showChild(it.Id, w, data)
        })
      }
    },
    initSearchP () {
      return new Promise((resolve, reject) => {
        if (this.$route.params.id) {
          projectPlanApi.getById({ Id: this.$route.params.id }).then(res => {
            if (res) {
              resolve(res)
            }
          }).catch((e) => {
            reject(e)
          })
        } else {
          this.warning('错误进入')
          this.$router.go(-1)
          reject(new Error('错误进入'))
        }
      })
    },
    reset() {
      // this.showSearch = false
      this.formValue = {}
    },
    // globlClickHideShowSearch () {
    //   this.showSearch = false
    // }
  },
  // watch: {
  //   showSearch(n, o) {
  //     if (n) {
  //       document.addEventListener('click', this.globlClickHideShowSearch, true)
  //     } else {
  //       document.removeEventListener('click', this.globlClickHideShowSearch, true)
  //     }
  //   }
  // }
}
</script>
<style scoped>
.divider {
  margin: 0;
}
.back-class {
  color: #00d1b2;
}
.headButton {
  text-align: right;
  padding-bottom: 10px;
}

.headButton >>> .title {
  float: left;
  font-width: normal;
  font-size: 20px;
}
.task-table-style >>> .vxe-body--row.col-red {
  background-color: #fee0e0;
  color: #e05c5c;
}
.task-table-style >>> .vxe-body--row.ok-col-red {
  background-color: #dbf3e7;
  color: #666666;
}
.task-table-style >>> .vxe-body--row.col-defa {
  color: #666666;
}
.vxe-icon--funnel:hover {
  color: #20a0ff;
  cursor: pointer;
}
</style>
